import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { reqLogin, reqGetUserInfo, reqLogout } from '@/api/user';



/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: '',
      avatar: '',
    },
    menuRoutes: staticRoutes
  }),

  actions: {
    // 登录  存储token
    async login (username: string, password: string) {
      const result = await reqLogin(username, password)
      // 将token 存到pinia中
      this.token = result.token
      // 数据持久化
      setToken(result.token)
    },
    // 获取用户信息
    async getInfo () {
      const result = await reqGetUserInfo();
      this.userInfo = result
    },

    // 退出登录
    async logout() {
      await reqLogout();
      this.reset()
    },

    reset () {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
      }
    },
	},
});
